import { getOssToken, getImageInfoByOcr } from '@/common/api/api.js'
import { uploadImageToOss } from './upload.js'
import CryptoTool from '@/common/utils/crypto/jscrypto.js'
import Compressor from 'compressorjs'

//是否是微信浏览器
function is_wechat_browser() {
	// #ifdef H5
	return /micromessenger/.test(navigator.userAgent.toLowerCase())
	// #endif
	// #ifndef H5
	return false
	// #endif
}
//是否是安卓系统
function is_android() {
	return /android/i.test(navigator.userAgent.toLowerCase())
}
//是否是iOS系统
function is_ios() {
	return /iphone|ipad|ipod/i.test(navigator.userAgent.toLowerCase())
}
/**
 * 验证密码必须为数字和字母组合，并且是6~18位
 */
function checkPassword(value) {
	return /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,18}$/.test(value)
}
/**
 * 验证6位纯数字支付密码
 */
function checkPayPassword(value) {
	return /^\d{6}$/.test(value)
}
/**
 * 封装的展示消息提示的方法
 * @param {string} title 提示内容
 * @param {number} duration 显示时间，默认2s
 * @param {Function} callback 消失回调
 */
function showToast(title = '', duration = 2000, callback) {
	uni.showToast({
		title,
		duration,
		icon: 'none',
	})
	if (callback) {
		setTimeout(() => {
			callback()
		}, duration)
	}
}

/**
 * 封装的加载中展示方法
 * @param {string} title 提示文字
 * @param {boolean} mask 是否不允许交互，默认允许
 */
function showLoading(title = '', mask = true) {
	uni.showLoading({
		title,
		mask
	})
}
/**
 * 隐藏加载提示
 */
function hideLoading() {
	uni.hideLoading()
}
/**
 * 去除字符串所有的空格
 * @param {string} value 原字符串
 */
function clearSpace(value) {
	return value.replace(/\s*/g, '')
}
/**
 * 去除字符串所有的空格和换行
 * @param {string} value 原字符串
 */
function clearAllSpace(value) {
	return value.replace(/[\s\n]/g, '')
}
/**
 * 选择图片
 * @param {Array} sourceType 支持拍照/从相册选择，默认两者都有
 */
function showSelectImage(sourceType = ['camera', 'album']) {
	return new Promise((resolve, reject) => {
		uni.chooseImage({
			count: 1,
			sourceType,
			sizeType: ['original', 'compressed'],
			success: function(res) {
				if (res.tempFiles.length > 0) {
					// #ifdef H5
					const file = res.tempFiles[0]
					imageCompressor(file).then(result => {
						console.log(result)
						resolve(result)
					}).catch(err => {
						reject(err)
					})
					// #endif
					// #ifndef H5
					const file = res.tempFilePaths[0]
					uni.compressImage({
						src: file,
						quality: 80,
						success: res => {
							console.log('压缩结果：', res)
							resolve(res.tempFilePath)
						},
						fail(err) {
							reject(err)
						}
					})
					// #endif
				} else {
					reject('无效的图片信息')
				}
			},
			fail(error) {
				reject(error)
			}
		});
	})
}

/**
 * 选择图片并上传到阿里oss
 */
async function uploadImage(sourceType = ['camera', 'album']) {
	const image = await showSelectImage(sourceType)
	const ossRes = await getOssToken()
	const ossConfig = ossRes.result
	const res = await uploadImageToOss(image, 'images', ossConfig.bucket, ossConfig.region, ossConfig.stsToken, ossConfig.accesskeyId, ossConfig.accesskeySecret)
	console.log('图片上传成功url：', res)
	return res
}
/**
 * 上传Base64图片到阿里oss
 */
async function uploadBase64Image(base64Data) {
	const ossRes = await getOssToken()
	const ossConfig = ossRes.result
	const res = await uploadImageToOss(base64Data, 'images', ossConfig.bucket, ossConfig.region, ossConfig.stsToken, ossConfig.accesskeyId, ossConfig.accesskeySecret)
	return res
}
/**
 * 图片ocr识别
 * @param {string} url 图片网络地址
 * @param {string} mode ocr识别类型 
 * idcard_front：身份证正面
 * idcard_back：身份证反面
 * bankcard：银行卡
 * business_license：营业执照
 */
async function getImageOcrInfo(url, mode) {
	let params = {}
	params.fileUrl = url
	if (mode == 'idcard_front' || mode == 'idcard_back') {
		params.apiType = '01'
		params.frontOrBack = mode == 'idcard_front' ? 'F' : 'B'
	} else if (mode == 'bankcard') {
		params.apiType = '02'
	} else if (mode == 'business_license') {
		params.apiType = '03'
	}
	try {
		const res = await getImageInfoByOcr(params)
		const ocrInfo = JSON.parse(res.result.data)
		const ocrRes = ocrInfo.words_result
		if (mode == 'bankcard') {
			//银行卡
			const bankOcrRes = ocrInfo.result
			if (uni.$uv.test.empty(bankOcrRes)) {
				return { mode, url }
			} else {
				const bankCardNo = clearSpace(bankOcrRes.bank_card_number)
				const ocr = { bankCardNo }
				return { mode, url, ocr }
			}
		} else {
			if (uni.$uv.test.empty(ocrRes)) {
				return { mode, url }
			} else {
				if (mode == 'idcard_front') {
					// 身份证正面信息
					//姓名
					const name = ocrRes['姓名'].words
					//身份证号
					const idcard = ocrRes['公民身份号码'].words
					//性别
					const sex = ocrRes['性别'].words
					//名族
					const nation = ocrRes['民族'].words
					//住址
					const address = ocrRes['住址'].words
					//返回ocr结果对象
					const ocr = { name, idcard, sex, nation, address }
					return { mode, url, ocr }
				} else if (mode == 'idcard_back') {
					// 身份证反面信息
					//开始日期
					let startDate = ocrRes['签发日期'].words
					//结束日期
					let endDate = ocrRes['失效日期'].words
					if (startDate) {
						startDate = formatDate_hg(startDate)
						if (endDate.includes('长') || endDate.includes('年月日')) {
							endDate = '长期'
						} else {
							endDate = formatDate_hg(endDate)
						}
					}
					//返回ocr结果对象
					const ocr = { startDate, endDate }
					return { mode, url, ocr }
				} else {
					// 营业执照识别结果
					//社会信用代码
					let busLicenseId = ocrRes['社会信用代码'].words
					//公司名称
					const company = ocrRes['单位名称'].words
					//法人
					const name = ocrRes['法人'].words
					//注册资本
					let money = ocrRes['注册资本'].words
					if (money.indexOf('万元') != -1) {
						money = money.split('万元')[0]
					} else {
						money = ''
					}
					//成立日期
					let startDate = ocrRes['成立日期'].words
					if (startDate != '无') {
						startDate = uni.$utils.format_ymd(startDate)
					}
					//结束日期
					let endDate = ocrRes['有效期'].words
					if (endDate != '无' && endDate != '年月日') {
						if (endDate.includes('长') || endDate.includes('年月日')) {
							endDate = '长期'
						} else {
							endDate = format_ymd(endDate)
						}
					} else {
						endDate = '长期'
					}
					//返回ocr结果对象
					const ocr = { busLicenseId, company, startDate, endDate, name, money }
					return { mode, url, ocr }
				}
			}
		}

	} catch (e) {
		return { mode, url }
	}
}
/**
 * 格式化姓名中间显示*号
 * @param { string } name 姓名
 * @return {string} 返回格式化后的字符串
 */
function formatName(name) {
	if (uni.$uv.test.empty(name) || name.length < 2) {
		return name
	}
	const start = name.slice(0, 1)
	if (name.length > 2) {
		const end = name.slice(-1)
		return `${start}${'*'.repeat(name.length - 2)}${end}`
	} else {
		return `${start}*`
	}
}
/**
 * 格式化银行卡号中间显示8个*号
 * @param { string } code 银行卡号
 * @return {string} 返回格式化后的字符串
 */
function formatBankCardNo(code) {
	if (uni.$uv.test.empty(code)) {
		return code
	} else if (code.length < 8) {
		return code
	}
	const startCode = code.slice(0, 4)
	const endCode = code.slice(-4)
	return `${startCode} **** **** ${endCode}`
}
/**
 * 格式化身份证号中间显示*号
 * @param { string } idCard 身份证号
 * @return {string} 返回格式化后的字符串
 */
function formatIdCard(idCard) {
	if (uni.$uv.test.empty(idCard)) {
		return idCard
	} else if (idCard.length < 10) {
		return idCard
	}
	const startCode = idCard.slice(0, 6)
	const endCode = idCard.slice(-4)
	return `${startCode}********${endCode}`
}
/**
 * 手机号脱敏
 * @param { string } tel 手机号
 * @return {string} 返回格式化后的字符串
 */
function formatTel(tel) {
	if (uni.$uv.test.empty(tel)) {
		return tel
	} else if (tel.length < 11) {
		return tel
	}
	const startCode = tel.slice(0, 3)
	const endCode = tel.slice(-4)
	return `${startCode}****${endCode}`
}
/**
 * 格式化“年月日”日期字符串为“xxxx-xx-xx格式”
 * @param {string} date 需要格式化的日期
 */
function format_ymd(date) {
	let time = date
	time = time.replace(/([年月])/g, '-');
	time = time.replace(/日/g, '');
	return time
}
/**
 * 复制
 * @param {string} data 复制的内容
 */
function copy(data) {
	if (uni.$uv.test.empty(data)) {
		uni.$utils.showToast('暂无可复制的内容')
		return
	}
	uni.setClipboardData({
		data,
		success() {
			uni.$utils.showToast('复制成功')
		}
	})
}
/**
 * 密码AES加密
 * @param {string} password 原始密码
 * @return {string} 加密后的密码
 */
function passwordEncrypt(password) {
	if (uni.$uv.test.empty(password)) {
		return ''
	}
	return CryptoTool.passwordEncrypt(password)
}
/**
 * 图片压缩
 * @param { File | Blob } file 文件/Blob对象
 * @param { number } quality 压缩质量 0~1
 * @param { number } maxWidth 最大宽度
 * @param { maxHeight } maxHeight 最大高度
 */
function imageCompressor(file, quality = 0.6, maxWidth = 750, maxHeight = 1080) {
	if (!file) {
		return Promise.reject('无效的图片资源')
	}
	return new Promise((resolve, reject) => {
		new Compressor(file, {
			quality,
			maxWidth,
			maxHeight,
			success(result) {
				return resolve(result)
			},
			error(error) {
				console.log(error.message);
				return reject(error.message)
			}
		})
	})
}
/* yyyymmdd时间格式化成yyyy-mm-dd */
function formatDate_hg(dateString) {
	return dateString.replace(/^(\d{4})(\d{2})(\d{2})$/, "$1-$2-$3")
}
/**
 * 调用系统发送短信
 * @param {string} phone 手机号
 * @param {string} content 短信内容
 */
function sendMessage(phone, content) {
	//#ifdef APP-PLUS
	let msg = plus.messaging.createMessage(plus.messaging.TYPE_SMS);
	msg.to = [phone];
	msg.body = content;
	plus.messaging.sendMessage(msg);
	// #endif
	//#ifdef H5
	window.location.href = `sms:${phone}`
	// #endif
}
export default {
	is_wechat_browser,
	is_android,
	is_ios,
	showToast,
	showLoading,
	hideLoading,
	checkPassword,
	showSelectImage,
	uploadImage,
	clearSpace,
	clearAllSpace,
	formatBankCardNo,
	format_ymd,
	copy,
	formatIdCard,
	passwordEncrypt,
	formatName,
	formatTel,
	uploadBase64Image,
	imageCompressor,
	getImageOcrInfo,
	checkPayPassword,
	sendMessage
}